"""
bg = (255,255,255)
            screen.blit(reg_title,((600 - reg_title.get_size()[0]) / 2, 10))
            screen.blit(username,((600 - username.get_size()[0]) / 2, 70))
            screen.blit(passwd,((600 - passwd.get_size()[0]) / 2, 150))
            pygame.draw.rect(screen,(0,153,153),(150,100,300,30),0)
            pygame.draw.rect(screen,(0,153,153),(150,180,300,30),0)
            if ispsw:
                inpt = un_input.render(f"{user_name}",True,(0,0,0),(0,153,153))
            else:
                inpt = un_input.render(f"{user_name}_",True,(0,0,0),(0,153,153))
            if ispsw:
                inpsw = un_input.render(f"{pass_wd.__len__() * '*'}_",True,(0,0,0),(0,153,153))
            else:
                inpsw = un_input.render(f"{pass_wd.__len__() * '*'}",True,(0,0,0),(0,153,153))
            screen.blit(inpt,((600 - inpt.get_size()[0]) / 2,100))
            screen.blit(inpsw,((600 - inpsw.get_size()[0]) / 2,180))
            screen.blit(info1,((600 - info1.get_size()[0]) / 2, 360))
            if user_name and not(ispsw):
                screen.blit(info2,((600 - info2.get_size()[0]) / 2, 320))
                
                
    request = req.get("https://www.thisisxd.tk/files/vos/users.json")
    users = json.loads(request.text)
    for user in users:
        if user["name"] == name:
            if user["passwd"] == passwd:
                console.log(user["uuid"])
                return user
    # 注册
    users += [
        {
            "uuid":uuid.uuid1(),
            "name":name,
            "passwd":passwd
        }
    ]
    user = json.dumps(users)
"""

import pygame
import requests as req
import json
import time
import uuid
import requests

    
    
api = None
x2 = 0
t5 = None
x3 = 0
user = ""
t6 = None
username = None
passwd = None
msg = None
user_dis = None
t114 = None
user_welcame = ""
value = 0
log = None

def login1(name,passwd):
    global log,api,t6,value
    log(name,passwd)
    value += 20
    #api.create(name,passwd)
    req = requests.get(f"http://124.222.63.135:8080/login/{name}/{passwd}")
    rn = json.loads(req.text)
    value += 20
    if rn["code"] == 404:
        req = requests.get(f"http://124.222.63.135:8080/reg/{name}/{passwd}")
        value += 10
        login1(name,passwd)
    else:
        value += 10
        log("UUID: ",rn["uuid"])
        api.setglobalvalue("user",{"uuid":rn["uuid"],"name":name})
        t6 = api.newThread("Welcame Display",lambda: welcame(user))
        value += 50
        last_login = api.get_data("login.time.latest",int(time.time()))
        log("Latest Login: ",last_login)
        with open(api.getpath("./auth.json"),"w") as f:
            f.write(json.dumps(api.getglobalvalue("user")))
    #print(value)
    
t7 = None
def welcame(username):
    global user_welcame,msg,user_dis,api,log

    user_name = "WELCAME BACK, " + username + "!"
    for user in user_name:
        user_welcame += user
        user_dis = msg.render(user_welcame,True,(0,0,0),(255,255,255))
        pygame.time.delay(100)

    last_login = api.set_data("login.time.latest",int(time.time()))
    api.setglobalvalue("scr","<defalut>")

def noliner2(speed = 0.19):
    global x3,t6,api,user,t7,value
    x1 = 240
    exit = 1
    while exit == 1:
        #print(1)
        x1 = value * 2 + 40
        x3 += (x1 - x3) / 2 * speed
        pygame.time.delay(30)
        if 240 - x3 <= 1:
            exit = 0
    x3 = 240
    
def noliner1(x1 = 250,speed = 0.25):
    global x2,t5,api,t114,username,passwd
    a = True
    while x1 - x2 >= 1:
        x2 += (x1 - x2) / 2 * speed
        pygame.time.delay(30)
        if a and x1-x2 <= 5:
            t5 = api.newThread("Value::Noliner",noliner2)
            a = False
    x2 = x1
    t114 = api.newThread("login",lambda:login1(username,passwd))
    



info = {
    "name":"XToolsBox Login",
    "version":"1.0",
    "info":"XToolsBox Plus 用户账户系统",
    "by":["This is XiaoDeng"]
}
events = []
class login():
    def pause(self):pass
    def unpause(self):pass
    paused = False
    def __init__(self,api,log,screen):
        self.api = api
        self.log = log
        self.screen = screen
        self.screen.fill((255,255,255))
    def onStart(self):
        global x2,user_dis,msg,user_welcame,user,log,username,passwd
        global api
        login114 = True
        try:
            with open(self.api.getpath("./auth.json"),"r") as f:
                self.api.setglobalvalue("user",json.load(f))
                self.api.setglobalvalue("scr","<default>")
                self.log(f.read(),self.api.getglobalvalue("scr"))
            login114 = False
        except Exception as e:
            self.log(e)
            
        log = self.log
        api = self.api
        msg = pygame.font.Font(self.api.getpath("./font.ttf"),20)
        user_dis = msg.render(user_welcame,True,(0,0,0),(255,255,255))
        screen = pygame.surface.Surface(self.api.getglobalvalue("config")["window.size"])
        bg = (255,255,255)
        screen.fill(bg)
        title = pygame.font.Font(self.api.getpath("./font.ttf"),25).render("LOGIN XTOOLSBOX+",True,(0,0,0),bg)
        screen.blit(title,(self.api.autocenter(title),10))
        msg1 = pygame.font.Font(self.api.getpath("./font.ttf"),25)
        username_title = msg.render("USERNAME",True,(0,0,0),bg)
        screen.blit(username_title,(self.api.autocenter(username_title),50))
        passwd_title = msg.render("PASSWORD",True,(0,0,0),bg)
        screen.blit(passwd_title,(self.api.autocenter(username_title),130))
        ispwd = False
        inputed = ""
        user_welcame = ""
        passwd = False
        while True and login114:
            if events.__len__() >= 1:
                event = events.pop(0)
                if event.type == pygame.KEYDOWN:
                    if event.key == 13:
                        if not(ispwd):
                            ispwd = True
                            username = inputed
                            user = username
                            inputed = ""
                        elif not(passwd):
                            passwd = inputed
                            self.thread1 = self.api.newThread("Bar::Enter",noliner1)
                            
                            
                    elif event.key == 8:
                        inputed = inputed[0:-1]
                    else:
                        inputed += event.unicode
                    self.log(event)
            pygame.draw.rect(screen,(0,153,153),(150,80,300,30),0)
            pygame.draw.rect(screen,(0,153,153),(150,160,300,30),0)
            if not(ispwd):
                obj = msg1.render(f"{inputed}_",True,(0,0,0),(0,153,153))
                screen.blit(obj,(self.api.autocenter(obj),80))
            elif not(passwd):
                obj = msg1.render(f"{username}",True,(0,0,0),(0,153,153))
                screen.blit(obj,(self.api.autocenter(obj),80))
                obj = msg1.render(f"{inputed.__len__() * '*'}_",True,(0,0,0),(0,153,153))
                screen.blit(obj,(self.api.autocenter(obj),160))
            else:
                obj = msg1.render(f"{username}",True,(0,0,0),(0,153,153))
                screen.blit(obj,(self.api.autocenter(obj),80))
                obj = msg1.render(f"{passwd.__len__()*'*'}",True,(0,0,0),(0,153,153))
                screen.blit(obj,(self.api.autocenter(obj),160))
                screen.blit(user_dis,(self.api.autocenter(user_dis),300))
                
                
            self.screen.blit(screen,(0,0))
            if passwd:
                pygame.draw.rect(self.screen,(0,0,153),(175,250,x2,40),2)
                pygame.draw.rect(self.screen,(0,0,155),(180,255,x3,30),0)
            pygame.time.delay(30)
                        
                    
class plugin():
    def __init__(self,api,log):
        global screen
        self.log = log
        self.api = api
        screen = self.api.addpage("<login>",login,f"{self.api.getpath('./tb')}/launch.png",settings = {"desktop.display":False,"desktop.title":True})
    def onEvent(self,event):
        global events
        events += [event]